/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainView.java
 *
 * Created on Nov 16, 2010, 9:46:16 AM
 */
package lightweighttransferagent;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.globus.ftp.DataSink;
import org.globus.ftp.DataSinkStream;
import org.globus.ftp.DataSource;
import org.globus.ftp.DataSourceStream;
import org.globus.ftp.exception.ClientException;
import org.globus.ftp.exception.ServerException;

/**
 * This is the main GUI for this application.
 * This GUI provide file transfer functions.
 * (ie. download file from GridFTP server and upload file to GridFTP server)
 * 
 * @author diluka
 */
public class MainView extends javax.swing.JFrame {

    private Login login;

    public MainView() {
        try {
            //to get OS look
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        //set to center
        this.setLocationRelativeTo(null);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroupFileTransfer = new javax.swing.ButtonGroup();
        jFileChooser = new javax.swing.JFileChooser();
        jLabel1 = new javax.swing.JLabel();
        jRadioButtonClien = new javax.swing.JRadioButton();
        jRadioButtonServer = new javax.swing.JRadioButton();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldFrom = new javax.swing.JTextField();
        jButtonBrowseFrom = new javax.swing.JButton();
        jButtonBrowseTo = new javax.swing.JButton();
        jTextFieldTo = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jButtonOK = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        jMenuBar = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemLogin = new javax.swing.JMenuItem();
        jMenuItemLogout = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        jMenuItemClose = new javax.swing.JMenuItem();
        jMenuHelp = new javax.swing.JMenu();
        jMenuItemAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Lightweight Transfer Agent");

        jLabel1.setText("File transfer from :");

        buttonGroupFileTransfer.add(jRadioButtonClien);
        jRadioButtonClien.setSelected(true);
        jRadioButtonClien.setText("client to server");
        jRadioButtonClien.setEnabled(false);
        jRadioButtonClien.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonClienActionPerformed(evt);
            }
        });

        buttonGroupFileTransfer.add(jRadioButtonServer);
        jRadioButtonServer.setText("server to client");
        jRadioButtonServer.setEnabled(false);
        jRadioButtonServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButtonServerActionPerformed(evt);
            }
        });

        jLabel2.setText("From   :");

        jButtonBrowseFrom.setText("Browse");
        jButtonBrowseFrom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseFromActionPerformed(evt);
            }
        });

        jButtonBrowseTo.setText("Browse");
        jButtonBrowseTo.setEnabled(false);
        jButtonBrowseTo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseToActionPerformed(evt);
            }
        });

        jLabel3.setText("To       :");

        jButtonOK.setText("OK");
        jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOKActionPerformed(evt);
            }
        });

        jLabel4.setText("Press OK to trasfer file");

        jMenuFile.setText("File");

        jMenuItemLogin.setText("Login");
        jMenuItemLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemLoginActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemLogin);

        jMenuItemLogout.setText("Logout");
        jMenuItemLogout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemLogoutActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemLogout);
        jMenuFile.add(jSeparator3);

        jMenuItemClose.setText("Close");
        jMenuItemClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemCloseActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemClose);

        jMenuBar.add(jMenuFile);

        jMenuHelp.setText("Help");

        jMenuItemAbout.setText("About");
        jMenuHelp.add(jMenuItemAbout);

        jMenuBar.add(jMenuHelp);

        setJMenuBar(jMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jRadioButtonServer)
                            .addComponent(jRadioButtonClien))))
                .addContainerGap(269, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextFieldFrom, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonBrowseFrom)
                .addGap(23, 23, 23))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldTo, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE))
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButtonOK, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonBrowseTo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(23, 23, 23))
            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRadioButtonClien)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jRadioButtonServer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBrowseFrom))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonBrowseTo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonOK)
                    .addComponent(jLabel4))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItemLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLoginActionPerformed
        login = new Login(this, true);
        login.setVisible(true);
    }//GEN-LAST:event_jMenuItemLoginActionPerformed

    private void jButtonBrowseFromActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseFromActionPerformed
        //popup 'open file' file chooser dialog
        int returnValue = jFileChooser.showOpenDialog(this);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            try {
                File sourceFile = jFileChooser.getSelectedFile();
                jTextFieldFrom.setText(sourceFile.getCanonicalPath());
            } catch (IOException ex) {
                System.out.println(ex.toString());
            }
        }
    }//GEN-LAST:event_jButtonBrowseFromActionPerformed

    private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
        boolean ok = true;
        if (jRadioButtonClien.isSelected()) {
            DataSource source = null;

            try {
                //create a DataSource implementation instance representing an interface to the local file
                source = new DataSourceStream(new FileInputStream(jTextFieldFrom.getText()));
            } catch (IOException ex) {
                System.out.println("could not access client source: " + ex.toString());
                ok = false;
            }

            if (ok) {
                try {
                    //tranferring file from client to server
                    login.getClient().put(jTextFieldTo.getText(), source, null);
                } catch (ServerException ex) {
                    System.out.println("Server exception putting file: " + ex.getMessage());
                    ok = false;
                } catch (ClientException ex) {
                    System.out.println("Client exception putting file: " + ex.getMessage());
                    ok = false;
                } catch (IOException ex) {
                    System.out.println("IO exception putting file: " + ex.getMessage());
                    ok = false;
                } catch (Exception ex) {
                    System.out.println("Error putting file: " + ex.getMessage());
                    ok = false;
                }

                if (ok) {
                    //if file transfer is success
                    JOptionPane.showMessageDialog(this, "Transfer successfully completed.", "Complete", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    //if fail to tarnsfer file
                    JOptionPane.showMessageDialog(this, "Error while uploading file.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                //if fail to creat DataSourceStream object
                JOptionPane.showMessageDialog(this, "Error while accessing client source.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } else if (jRadioButtonServer.isSelected()) {
            DataSink sink = null;

            try {
                //create a DataSink implementation instance representing an interface to the local file
                sink = new DataSinkStream(new FileOutputStream(jTextFieldTo.getText()));
            } catch (FileNotFoundException ex) {
                System.out.println("could not access client destination: " + ex.toString());
                ok = false;
            }

            if (ok) {
                try {
                    //transferring file from server to client
                    login.getClient().get(jTextFieldFrom.getText(), sink, null);
                } catch (IOException ex) {
                    System.out.println("IO exception getting file: " + ex.getMessage());
                    ok = false;
                } catch (ClientException ex) {
                    System.out.println("Client exception getting file: " + ex.getMessage());
                    ok = false;
                } catch (ServerException ex) {
                    System.out.println("Server exception getting file: " + ex.getMessage());
                    ok = false;
                } catch (Exception ex) {
                    System.out.println("Error getting file: " + ex.getMessage());
                    ok = false;
                }

                if (ok) {
                    //if file transfer is success
                    JOptionPane.showMessageDialog(this, "Transfer successfully completed.", "Complete", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    //if fail to transfer file
                    JOptionPane.showMessageDialog(this, "Error while downloading file.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                //if fail to creat DataSinkStream object
                JOptionPane.showMessageDialog(this, "Error while accessing client destination.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            //if user dose not sellect whether file transfer is from client to server or server to client
            JOptionPane.showMessageDialog(this, "Select a transfer type.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonOKActionPerformed

    private void jButtonBrowseToActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseToActionPerformed
        //popup 'save file' file chooser dialog
        int returnValue = jFileChooser.showSaveDialog(this);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            try {
                File destinationFile = jFileChooser.getSelectedFile();
                jTextFieldTo.setText(destinationFile.getCanonicalPath());
            } catch (IOException ex) {
                System.out.println(ex.toString());
            }
        }
    }//GEN-LAST:event_jButtonBrowseToActionPerformed

    private void jMenuItemLogoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLogoutActionPerformed
        boolean ok = true;

        try {
            //closing socket to server
            login.getClient().close();
            this.setDefault(false);
        } catch (IOException ex) {
            System.out.println("IO exception logout: " + ex.getMessage());
            ok = false;
        } catch (ServerException ex) {
            System.out.println("Server exception logout: " + ex.getMessage());
            ok = false;
        }
        if (ok) {
            //if socket is closed successfully
            JOptionPane.showMessageDialog(this, "Successfully logout.", "Logout", JOptionPane.INFORMATION_MESSAGE);
        } else {
            //if fail to close the connection
            JOptionPane.showMessageDialog(this, "Error while logout.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jMenuItemLogoutActionPerformed

    private void jMenuItemCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemCloseActionPerformed
        //close the application
        this.dispose();
    }//GEN-LAST:event_jMenuItemCloseActionPerformed

    private void jRadioButtonClienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonClienActionPerformed
        jButtonBrowseFrom.setEnabled(true);
        jButtonBrowseTo.setEnabled(false);
    }//GEN-LAST:event_jRadioButtonClienActionPerformed

    private void jRadioButtonServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonServerActionPerformed
        jButtonBrowseFrom.setEnabled(false);
        jButtonBrowseTo.setEnabled(true);
    }//GEN-LAST:event_jRadioButtonServerActionPerformed

    public void setDefault(boolean enable) {
        if (enable) {
            jRadioButtonClien.setEnabled(true);
            jRadioButtonServer.setEnabled(true);
            jRadioButtonClien.setSelected(true);
            jButtonBrowseFrom.setEnabled(true);
            jButtonBrowseTo.setEnabled(false);
        } else {
            jRadioButtonClien.setSelected(true);
            jRadioButtonClien.setEnabled(false);
            jRadioButtonServer.setEnabled(false);
            jButtonBrowseFrom.setEnabled(true);
            jButtonBrowseTo.setEnabled(false);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroupFileTransfer;
    private javax.swing.JButton jButtonBrowseFrom;
    private javax.swing.JButton jButtonBrowseTo;
    private javax.swing.JButton jButtonOK;
    private javax.swing.JFileChooser jFileChooser;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenuBar jMenuBar;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JMenu jMenuHelp;
    private javax.swing.JMenuItem jMenuItemAbout;
    private javax.swing.JMenuItem jMenuItemClose;
    private javax.swing.JMenuItem jMenuItemLogin;
    private javax.swing.JMenuItem jMenuItemLogout;
    private javax.swing.JRadioButton jRadioButtonClien;
    private javax.swing.JRadioButton jRadioButtonServer;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JTextField jTextFieldFrom;
    private javax.swing.JTextField jTextFieldTo;
    // End of variables declaration//GEN-END:variables
}
